<template>
  <div class="index">
    <!-- 顶部 -->
    <div class="top"><Admin></Admin></div>
    <!-- bottom -->
    <div class="bottom">
      <div class="left"><SideNav></SideNav></div>
      <div class="right">
        <div class="content">
          <el-scrollbar style="height: 100%;">
            <!-- 当前位置 -->
            <div class="current_position" ref="pronbit">
              <p class="breadcrumb">当前位置 :</p>
              <el-breadcrumb separator="/">
                <el-breadcrumb-item class="up">生活服务</el-breadcrumb-item>
                <el-breadcrumb-item>活动广告</el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <div class="userlist">
              <!-- banner -->
              <div class="banner">
                <div class="title">首页banner</div>
                <el-form ref="bannerForm" :model="bannerForm" label-width="80px">
                  <el-form-item label="">
                    <el-radio-group v-model="bannerForm.sort" @change="sortChange($event)">
                      <el-radio :label="1">排序1</el-radio>
                      <el-radio :label="2">排序2</el-radio>
                      <el-radio :label="3">排序3</el-radio>
                      <el-radio :label="4">排序4</el-radio>
                      <el-radio :label="5">排序5</el-radio>
                      <el-radio :label="6">排序6</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="标题">
                    <el-input v-model="bannerForm.title" class="channelName"></el-input>
                  </el-form-item>
                  <el-form-item label="banner : "  class="upload">
                    <el-upload class="uploadBox"
                      list-type="picture-card"
                      :file-list="fileListBanner"
                      action
                      :limit="1"
                      :http-request="handleUploadBanner"
                      :on-preview="handlePictureCardPreviewBanner"
                      :on-remove="handleRemoveBanner"
                      :class="{hide:hideUploadBanner}">
                      <i class="el-icon-plus"></i>
                    </el-upload>
                    <div class="tip">（可以上传一张图片，建议尺寸200*710）</div>
                    <el-dialog :visible.sync="dialogVisibleBanner">
                      <img width="100%" :src="dialogImageUrlBanner" alt="">
                    </el-dialog>
                  </el-form-item>
                  <el-form-item label="类型 : ">
                    <el-radio-group v-model="bannerForm.jumpType" @change="getBanner1Enable()">
                      <el-radio :label="1">不跳转</el-radio>
                      <el-radio :label="2">原生</el-radio>
                      <el-radio :label="3">H5</el-radio>
                    </el-radio-group>
                    <el-input class="link_url" v-model="bannerForm.url" v-if="contentBox" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="附加字段 : ">
                    <el-input v-model="bannerForm.informationPostId" class="channelName" placeholder="可不填"></el-input>
                    <span style="padding-left: 20px;">ps:填写内容，请联系管理员</span>
                  </el-form-item>
                  <el-form-item label="开始时间 : ">
                    <el-date-picker
                      v-model="bannerForm.startTime"
                      type="datetime"
                      placeholder="选择开始日期"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :default-time="'00:00:01'">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="结束时间 : ">
                    <el-date-picker
                      v-model="bannerForm.endTime"
                      type="datetime"
                      placeholder="选择结束日期"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :default-time="'23:59:59'">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="banner()">保存</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <!-- 发布页轮播图-->
              <div class="popups">
                <div class="title">发布页轮播图</div>
                <el-form ref="issueForm" :model="issueForm" label-width="80px">
                  <el-form-item label="标题">
                    <el-input v-model="issueForm.title" class="channelName"></el-input>
                  </el-form-item>
                  <el-form-item label="banner : "  class="upload">
                    <el-upload class="uploadBox"
                      list-type="picture-card"
                      :file-list="fileListIssue"
                      action
                      :limit="1"
                      :http-request="handleUploadIssue"
                      :on-preview="handlePictureCardPreviewIssue"
                      :on-remove="handleRemoveIssue"
                      :class="{hide:hideUploadIssue}">
                      <i class="el-icon-plus"></i>
                    </el-upload>
                    <div class="tip">（可以上传一张图片，建议尺寸200*710）</div>
                    <el-dialog :visible.sync="dialogVisibleIssue">
                      <img width="100%" :src="dialogImageUrlIssue" alt="">
                    </el-dialog>
                  </el-form-item>
                  <el-form-item label="开始时间 : ">
                    <el-date-picker
                      v-model="issueForm.startTime"
                      type="datetime"
                      placeholder="选择日期时间"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :default-time="'00:00:01'">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="结束时间 : ">
                    <el-date-picker
                      v-model="issueForm.endTime"
                      type="datetime"
                      placeholder="选择结束日期"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :default-time="'23:59:59'">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="issue()">保存</el-button>
                  </el-form-item>
                </el-form>
               </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import Admin from '@/components/Admin.vue'
  import SideNav from '@/components/SideNav.vue'

  export default {
    name: 'Banner',
    components:{
      Admin,
      SideNav
    },
    data () {
      return {
        bannerList:[],//banner列表
        bannerForm: {//首页banner表单
          id:null,//banner的id值
          sort:1,//banner排序
          title: null,//标题
          address:null,//图片地址
          jumpType:1,//跳转类型
          url:null,//图片跳转地址
          informationPostId:null,//附加字段--帖子id
          startTime:null,//开始时间
          endTime:null,//结束时间
        },
        dialogImageUrlBanner: '',//预览banner
        dialogVisibleBanner: false,//预览banner弹窗
        hideUploadBanner: false,//隐藏banner上传图标的变量
        limitCountBanner:1,//banner受限长度
        fileListBanner: [],//banner地址
        contentBox:false,//隐藏banner的链接输入框
        issueList:[],//banner列表
        issueForm:{//发布页轮播图表单
          id:null,//发布页轮播的id值
          title: null,//标题
          address:null,//图片地址
          startTime:null,//开始时间
          endTime:null,//结束时间
        },
        dialogImageUrlIssue: '',//预览banner
        dialogVisibleIssue: false,//预览banner弹窗
        hideUploadIssue: false,//隐藏banner上传图标的变量
        limitCountIssue:1,//banner受限长度
        fileListIssue: [],//banner地址
      }
    },
    mounted() {
      this.getBannerList();
      this.getIssueList();
    },
    methods: {
      //获取banner列表
      getBannerList(){
        this.$axios.post(this.baseURL1+'admin/banner/list',{
          "requestSource":"PC",
          "page": 1,
          "size":100,
          "flag":1,//轮播图状态 1-首页 2-发布信息
        }).then((res)=>{
          if(res.data.code==0){
            console.log("banner:",res.data.data.records);
            this.bannerList = res.data.data.records;
            //默认显示排序为1的banner
            for(var i=0;i<this.bannerList.length;i++){
              if(this.bannerList[i].sort==1){
                this.bannerForm.id =  this.bannerList[i].id;//banner的id值
                this.bannerForm.sort =  this.bannerList[i].sort;//排序
                this.bannerForm.title = this.bannerList[i].title;//标题
                this.bannerForm.address = this.bannerList[i].address;//banner图片 地址
                this.fileListBanner = []//图片地址清空
                this.fileListBanner.push({ url: this.bannerForm.address });//banner图片 地址
                this.hideUploadBanner = this.fileListBanner.length >= this.limitCountBanner;//隐藏上传图标
                this.bannerForm.jumpType = this.bannerList[i].jumpType//类型
                if(this.bannerForm.jumpType==2||this.bannerForm.jumpType==3){//banner的类型选择与否的输入框
                  this.contentBox = true;
                  this.bannerForm.url = this.bannerList[i].url;//类型的跳转链接
                }else{
                  this.contentBox = false;
                }
                this.bannerForm.informationPostId = this.bannerList[i].informationPostId//附加字段
                this.bannerForm.startTime = this.bannerList[i].startTime;//banner1的开始时间
                this.bannerForm.endTime = this.bannerList[i].endTime;//banner1的结束时间
              }
            }
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      //点击排序选项
      sortChange(e){
        //console.log(e)
        this.bannerForm.id = null
        this.bannerForm.title = null
        this.bannerForm.address = null
        this.fileListBanner = []//图片地址清空
        this.hideUploadBanner = this.fileListBanner.length >= this.limitCountBanner;//显示上传图标
        this.bannerForm.jumpType = null
        this.bannerForm.url = null
        this.bannerForm.informationPostId = null
        this.bannerForm.startTime = null
        this.bannerForm.endTime = null
        //遍历banner列表 当列表的排序值和页面的排序值一致时  赋值类容给该banner数组
        for(var i=0;i<this.bannerList.length;i++){
          if(this.bannerList[i].sort==e){
            //console.log(this.bannerList[i].sort)
            this.bannerForm.id =  this.bannerList[i].id;//banner的id值
            this.bannerForm.sort =  this.bannerList[i].sort;//排序
            this.bannerForm.title = this.bannerList[i].title;//标题
            this.bannerForm.address = this.bannerList[i].address;//banner图片 地址
            this.fileListBanner.push({ url: this.bannerForm.address });//banner图片 地址
            this.hideUploadBanner = this.fileListBanner.length >= this.limitCountBanner;//隐藏上传图标
            this.bannerForm.jumpType = this.bannerList[i].jumpType//类型
            if(this.bannerForm.jumpType==2||this.bannerForm.jumpType==3){//banner的类型选择与否的输入框
              this.contentBox = true;
              this.bannerForm.url = this.bannerList[i].url;//类型的跳转链接
            }else{
              this.contentBox = false;
            }
            this.bannerForm.informationPostId = this.bannerList[i].informationPostId//附加字段
            this.bannerForm.startTime = this.bannerList[i].startTime;//banner1的开始时间
            this.bannerForm.endTime = this.bannerList[i].endTime;//banner1的结束时间
          }
        }

      },
      // 获取签名
      getOssToken(){
        var _self = this;
        return new Promise((resolve,reject)=>{
          this.$axios.post(this.baseURL1+'getJsOssToken',{
            "requestSource":"PC"
          }).then(function(res){
            if(res.data.code==1){
              console.log(res,"通行证");
              _self.aliyunOssToken = res.data.data;
              resolve()
            }
          }).catch(function(error){
            console.log(error);
          })
        })
      },
      // 删除banner图
      handleRemoveBanner(file) {
        console.log(this.fileListBanner);
        console.log(file);
       for(var j=0; j<this.fileListBanner.length;j++){
          if(file.uid == this.fileListBanner[j].uid ){
             this.fileListBanner.splice(j,1);
          }
        }
        this.hideUploadBanner = this.fileListBanner.length >= this.limitCountBanner;//显示上传图标
      },
      // 预览banner图
      handlePictureCardPreviewBanner(file) {
        this.dialogImageUrlBanner = file.url;
        this.dialogVisibleBanner = true;
      },
      // 提交banner图
      handleUploadBanner(option){
        this.getOssToken().then(res=>{
          var _self = this;
          var getSuffix = option.file.name;
          var filename = new Date().getTime() + getSuffix.substring(getSuffix.lastIndexOf("."),getSuffix.length);
          var formData = new FormData();//注意formData里append添加的键的大小写
          formData.append('key', _self.aliyunOssToken.dir + filename); //存储在oss的文件路径
          formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); //accessKeyId
          formData.append('policy', _self.aliyunOssToken.policy); //policy
          formData.append('Signature', _self.aliyunOssToken.signature); //签名
          formData.append('success_action_status', 200); //成功后返回的操作码
          formData.append("file", option.file);//文件
          var url = _self.aliyunOssToken.host; //url
          var fileUrl = '';
          fileUrl = _self.aliyunOssToken.host +'/'+ _self.aliyunOssToken.dir + filename; //fileUrl文件路径
          this.$axios.post(url, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          }).then((res) => {
            if(res.status==200){
              this.$message({
                message: '上传成功',
                type: 'success'
              });

              this.fileListBanner.push({ url: fileUrl });
              console.log(this.fileListBanner,"图片上传成功，图片列表");
              this.hideUploadBanner = this.fileListBanner.length >= this.limitCountBanner;//隐藏上传图标
              //赋值
              this.bannerForm.address = this.fileListBanner[0].url;
            }else{
              this.$message.error('上传失败！请重新上传');
            }
          })
          .catch((err) => {
             console.log("err:",err)
          })
        })
      },
      // 修改banner的跳转链接
      getBanner1Enable(){
        console.log(this.bannerForm.jumpType,"banner链接的值")
        if(this.bannerForm.jumpType==2||this.bannerForm.jumpType==3){
          this.contentBox = true;
        }else{
          this.contentBox = false;
        }
      },
      //根据是否有id值判断是保存还是修改banner
      banner(){
        console.log(this.bannerForm)
        if(!this.bannerForm.id){
          this.bannerSubmit()//保存新添加的banner
        }else{
          this.bannerChange()//修改banner
        }
      },
      //保存banner 没有id
      bannerSubmit() {
        console.log('保存!',this.bannerForm);
        this.$axios.post(this.baseURL1+'admin/banner/add',{
          "requestSource":"PC",
          "type":1,//轮播图状态 1-首页banner 2-发布信息
          "sort":this.bannerForm.sort,//banner排序
          "title": this.bannerForm.title,//标题
          "address":this.bannerForm.address,//图片地址
          "jumpType":this.bannerForm.jumpType,//跳转类型
          "url":this.bannerForm.url,//图片跳转地址
          "informationPostId":this.bannerForm.informationPostId,//附加字段--帖子id
          "startTime":this.bannerForm.startTime,//开始时间
          "endTime":this.bannerForm.endTime,//结束时间
        }).then((res)=>{
          if(res.data.code==0){
            this.$message({
              message: '保存成功',
              type: 'success'
            });
            this.getBannerList();
          }else{
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      //修改Banner  有id
      bannerChange() {
        console.log('修改!',this.bannerForm);
        this.$axios.post(this.baseURL1+'admin/banner/update',{
          "requestSource":"PC",
          "type":1,//轮播图状态 1-首页banner 2-发布信息
          "id":this.bannerForm.id,//banner  id
          "sort":this.bannerForm.sort,//banner排序
          "title": this.bannerForm.title,//标题
          "address":this.bannerForm.address,//图片地址
          "jumpType":this.bannerForm.jumpType,//跳转类型
          "url":this.bannerForm.url,//图片跳转地址
          "informationPostId":this.bannerForm.informationPostId,//附加字段--帖子id
          "startTime":this.bannerForm.startTime,//开始时间
          "endTime":this.bannerForm.endTime,//结束时间
        }).then((res)=>{
          if(res.data.code==0){
            this.$message({
              message: '保存成功',
              type: 'success'
            });
            //location.reload()
            this.getBannerList();
          }else{
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },

      //获取发布页轮播
      getIssueList(){
        this.$axios.post(this.baseURL1+'admin/banner/list',{
          "requestSource":"PC",
          "page": 1,
          "size":100,
          "flag":2,//轮播图状态 1-首页 2-发布信息
        }).then((res)=>{
          if(res.data.code==0){
            this.issueForm.id = res.data.data.records[0].id;
            this.issueForm.title = res.data.data.records[0].title;
            this.issueForm.address = res.data.data.records[0].address;
            this.fileListIssue = []//图片地址清空
            this.fileListIssue.push({ url: this.issueForm.address });//banner图片 地址
            this.hideUploadIssue = this.fileListIssue.length >= this.limitCountIssue;//隐藏上传图标
            this.issueForm.startTime = res.data.data.records[0].startTime;
            this.issueForm.endTime = res.data.data.records[0].endTime;
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      //删除发布轮播图
      handleRemoveIssue(file) {
        console.log(this.fileListIssue);
        console.log(file);
        for(var j=0; j<this.fileListIssue.length;j++){
          if(file.uid == this.fileListIssue[j].uid ){
            this.fileListIssue.splice(j,1);
          }
        }
       this.hideUploadIssue = this.fileListIssue.length >= this.limitCountIssue;//显示上传图标
      },
      //预览发布轮播图
      handlePictureCardPreviewIssue(file){
        this.dialogImageUrlIssue = file.url;
        this.dialogVisibleIssue = true;
      },
      //提交发布轮播图
      handleUploadIssue(option){
        this.getOssToken().then(res=>{
          var _self = this;
          var getSuffix = option.file.name;
          var filename = new Date().getTime() + getSuffix.substring(getSuffix.lastIndexOf("."),getSuffix.length);
          var formData = new FormData();//注意formData里append添加的键的大小写
          formData.append('key', _self.aliyunOssToken.dir + filename); //存储在oss的文件路径
          formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); //accessKeyId
          formData.append('policy', _self.aliyunOssToken.policy); //policy
          formData.append('Signature', _self.aliyunOssToken.signature); //签名
          formData.append('success_action_status', 200); //成功后返回的操作码
          formData.append("file", option.file);//文件
          var url = _self.aliyunOssToken.host; //url
          var fileUrl = '';
          fileUrl = _self.aliyunOssToken.host +'/'+ _self.aliyunOssToken.dir + filename; //fileUrl文件路径
          this.$axios.post(url, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          }).then((res) => {
            if(res.status==200){
              this.$message({
                message: '上传成功',
                type: 'success'
              });

              this.fileListIssue.push({ url: fileUrl });
              console.log(this.fileListIssue,"图片上传成功，图片列表");
              this.hideUploadIssue = this.fileListIssue.length >= this.limitCountIssue;//隐藏上传图标
              //赋值
              this.issueForm.address = this.fileListIssue[0].url;
            }else{
              this.$message.error('上传失败！请重新上传');
            }
          })
          .catch((err) => {
             console.log("err:",err)
          })
        })
      },
      //保存发布页轮播图
      issue(){
        console.log(this.issueForm)
        if(!this.issueForm.id){
          this.issueSubmit()//保存新添加的发布页轮播
        }else{
          this.issueChange()//修改发布页轮播
        }
      },
      //保存发布页轮播 没有id
      issueSubmit(){
        this.$axios.post(this.baseURL1+'admin/banner/add',{
          "requestSource":"PC",
          "type":2,//轮播图状态 1-首页banner 2-发布信息
          "jumpType":1,
          "sort":1,
          "informationPostId":0,
          "title": this.issueForm.title,//标题
          "address":this.issueForm.address,//图片地址
          "startTime":this.issueForm.startTime,//开始时间
          "endTime":this.issueForm.endTime,//结束时间
        }).then((res)=>{
          if(res.data.code==0){
            this.$message({
              message: '保存成功',
              type: 'success'
            });
            this.getIssueList()
          }else{
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      //修改发布页轮播  有id
      issueChange(){
        this.$axios.post(this.baseURL1+'admin/banner/update',{
          "requestSource":"PC",
          "type":2,//轮播图状态 1-首页banner 2-发布信息
          "jumpType":1,
          "sort":1,
          "informationPostId":0,
          "id": this.issueForm.id,//id
          "title": this.issueForm.title,//标题
          "address":this.issueForm.address,//图片地址
          "startTime":this.issueForm.startTime,//开始时间
          "endTime":this.issueForm.endTime,//结束时间
        }).then((res)=>{
          if(res.data.code==0){
            this.$message({
              message: '保存成功',
              type: 'success'
            });
            this.getIssueList()
          }else{
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
    },
  }

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  @import '@/assets/css/index.scss'; //这个分号一定要写，要不会报错
  @import '@/assets/css/user.scss'; //这个分号一定要写，要不会报错
  .userlist{
    padding: 0;
    .popups,
    .banner{
      width: 100%;
      height: auto;
      box-sizing: border-box;
      margin-bottom: 20px;
      .title{
        line-height: 30px;
        background-color: #cfcfcf;
        padding: 0 10px;
        box-sizing: border-box;
        margin-bottom: 10px;
      }
      .img_popup{
        width: 80px;
        height: 80px;
        display: inline-block;
        img{
          width: 100%;
        }
      }
      .link_url{
        width: 300px;
      }
      >>> .el-form{
        background-color: #FFFFFF;
      }
      >>> .el-form-item__label{
        width: 110px!important;
      }
      >>> .el-upload--picture-card,
      >>> .el-upload-list--picture-card .el-upload-list__item{
        width: 284px;
        height: 80px;
        line-height: 80px;
      }
      >>> .el-button--primary{
        background-color: #fc7656;
        color: #fff;
        height: 35px;
        padding: 0px 20px;
        border: 1px solid #fc7656;
        box-sizing: border-box;
        margin-left: 30px;
      }
      >>> .popup_switch{
        line-height: 50px;
      }
      >>> .el-form-item{
        margin-bottom: 10px;
      }
      >>> .el-form-item__content{
        line-height: 0;
      }
      >>> .el-radio-group{
        line-height: 45px;
      }
    }
    .popups{
      >>> .el-upload--picture-card,
      >>> .el-upload-list--picture-card .el-upload-list__item{
        width: 284px;
        height: 80px;
        line-height: 80px;
      }
      .channelName{
        width: 300px;
      }
      .upload{
        width: auto;
        box-sizing: border-box;
        >>> .el-upload-list__item-status-label{
          display: none;
        }
        .tip{
          color: #FC7656;
          line-height: 20px;
          margin-left: 20px;
          display: inline-block;
          font-size: 10px;
        }
      }
    }
    .banner{
      .banner_border{
        width: 100%;
        height: 15px;
        background-color: #f0f1f6;
      }
      >>> .el-tabs__nav-wrap::after{
        display: none;
      }
      >>> .el-tabs__item{
        width: 85px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        padding: 0;
        margin: 0 10px;
      }
      >>> .el-tabs__item:hover{
        color: #fc7656;
      }
      >>> .el-tabs__item.is-active{
        color: #fc7656;
      }
      >>> .el-tabs__active-bar{
        background-color: transparent;
      }
      .channelName{
        width: 220px;
      }
      .upload{
        width: auto;
        height: 110px;
        box-sizing: border-box;
        >>> .el-upload-list__item-status-label{
          display: none;
        }
        .tip{
          color: #FC7656;
          line-height: 20px;
          margin-left: 20px;
          display: inline-block;
          font-size: 10px;
        }
      }
    }

  }
  .hide{
    >>> .el-upload--picture-card{
      display: none;
    }
  }
</style>
